package com.guang.syncronized.review;

import org.openjdk.jol.info.ClassLayout;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.concurrent.TimeUnit;

/**
 * @Description 默认不开启偏向延迟。在进入到同步块中去会升级成轻量级锁
 *              证明：调用wait方法直接升级成重量级锁
 * @Author liguang
 * @Date 2022/10/22/08:27
 */
public class SyncronziedReviewTestTwo {
    private final static Logger logger = LoggerFactory.getLogger(SyncronziedReviewTestTwo.class);
    static Object lock = new Object();
    static volatile boolean flag = false;
    public static void main(String[] args) throws InterruptedException {
        logger.info("主线程启动的时候，JVM默认开启不可偏向");
        logger.info("打印当前对象的对象头，不可偏向的偏向锁，{}",ClassLayout.parseInstance(lock).toPrintable());

        new Thread(()->{
            synchronized (lock){
                while (!flag){
                    logger.info("打印当前对象的对象头，000为轻量级锁。，{}",ClassLayout.parseInstance(lock).toPrintable());
                    try {
                        lock.wait();
                        logger.info("打印当前对象的对象头，010为重量级锁。，{}",ClassLayout.parseInstance(lock).toPrintable());
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
            }
        },"t1").start();

        TimeUnit.SECONDS.sleep(15);

        new Thread(()->{
            synchronized (lock){
                flag = true;
                lock.notify();
            }
        },"t2").start();


    }
}
